//! Holds information on a single game, providing access to header 
//! information and the sequence of moves.
//!

use textwrap;
use regex::Regex;

use std::collections::HashMap;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;

use super::board::filter::BoardFilter;
use super::board::Board;
use super::moves;

/// This struct holds information about a game as loaded from a PGN file.
///
/// There are three pieces of information provided.
///
/// 1. The header field provides access to the header information from the PGN
/// file. The header field is returned as a normal 
/// [`HashMap`](std::collections::HashMap).
///
/// 2. [`self::total_half_moves()`] returns the number of half moves of the game.
///
/// 3. [`self::iter()`] provides access to an iterator, which steps through 
/// the individual moves of the game. The iterator returns a pair, consisting 
/// of (current board position, next move).
///
pub struct Game {
    /// The header field holds information from the PGN header.
    ///
    /// Typical fields include "White" and "Black" for the names of the
    /// players, "Date" and "Event" for when the game occurred, and
    /// "Result", giving the result of the game.
    ///
    /// # Example
    ///
    /// Print the name of the 'White' player in all games, where given:
    /// ```no_run
    /// # let games = pgn_filter::Games::new();
    /// for game in games.iter() {
    ///   if let Some(name) = game.header.get("White") {
    ///     println!("White: {}", name);
    ///   }
    /// }
    /// ```
    ///
    /// # Error
    ///
    /// Header is a HashMap, and the keys depend on the contents of the
    /// PGN file, so an error can be raised for a missing key.
    ///
    pub header: HashMap<String, String>,
    moves: Vec<Box<dyn moves::Move>>,
    result: String,
}

impl Clone for Game {
    fn clone(&self) -> Self {
        let mut clone = Game {
            header: HashMap::new(),
            moves: vec![],
            result: String::from(""),
        };

        for (key, val) in self.header.iter() {
            clone.header.insert(key.clone(), val.clone());
        }

        let matcher = moves::Matches::new(); // needed to build new copies of moves
        for mv in &self.moves {
           let cloned_move = matcher.new_move(&mv.to_string()).unwrap();
           clone.moves.push(cloned_move);
        }
        
        clone.result = self.result.clone();

        clone
    }
}

impl Game {
    /// Reads a single game from a PGN file.
    /// Returns None if no game was found, i.e. the file is empty.
    ///
    /// # Error
    ///
    /// An error is returned if there is a problem with the pgn file or definition.
    ///
    pub(super) fn from_pgn(reader: &mut BufReader<File>, matcher: &moves::Matches) -> std::io::Result<Option<Game>> {
        // matches a PGN header line
        let header_line = Regex::new("\\[(\\w+) \"(.*)\"\\]").unwrap();

        let mut game = Game {
            header: HashMap::new(),
            moves: vec![],
            result: String::from(""),
        };

        let mut line = "".to_string();
        // ignore blank lines
        loop {
            let len = &reader.read_line(&mut line)?;
            if *len == 0 {
                return Ok(None); // no game read on EOF
            }
            line = line.trim().to_string();
            if !line.is_empty() {
                break;
            }
        }
        // read the header
        while let Some(captures) = header_line.captures(&line) {
            game.header
                .insert(captures[1].to_string(), captures[2].to_string());
            line = "".to_string();
            let len = &reader.read_line(&mut line)?;
            if *len == 0 {
                return Ok(Some(game)); // game read on EOF
            }
            line = line.trim().to_string();
            if line.is_empty() {
                break;
            }
        }
        // ignore blank lines
        loop {
            line = line.trim().to_string();
            if !line.is_empty() {
                break;
            }
            line = "".to_string();
            let len = &reader.read_line(&mut line)?;
            if *len == 0 {
                return Ok(Some(game)); // game read on EOF
            }
        }
        // read the moves
        let mut move_str = "".to_string();
        loop {
            line = line.trim().to_string();
            // remove part of line after ; 
            if let Some(index) = line.find(';') {
                line.truncate(index);
            }
            if line.is_empty() || line.starts_with("%") {
                break;
            }
            move_str.push_str(&line);
            move_str.push(' ');
            line = "".to_string();
            let len = &reader.read_line(&mut line)?;
            if *len == 0 {
                break;
            }
        }
        // delete comments { ... }
        matcher.comment.replace_all(&move_str, "");
        // delete NAG $ddd..d
        matcher.nag.replace_all(&move_str, "");
        // parse the moves and add to game
        let move_number = Regex::new("\\^\\d+").unwrap(); // move numbers start with digits
        for token in move_str.split(' ') {
            let token = token.trim();
            if !token.is_empty() {
                if token == "1-0" || token == "0-1" || token == "1/2-1/2" || token == "*" {
                    game.result = token.to_string().clone();
                } else if !move_number.is_match(&token) {
                    // ignore move numbers
                    if matcher.is_valid(&token) {
                        game.moves.push(matcher.new_move(&token).unwrap());
                    }
                }
            }
        }

        // Return None instead of an empty game
        if game.header.is_empty() && game.moves.is_empty() {
            Ok(None)
        } else {
            Ok(Some(game))
        }
    }

    /// Returns true if game reaches a position which matches the given filter.
    pub(super) fn meets_filter(&self, filter: &BoardFilter) -> bool {
        let mut board = self.start_position();

        for mv in self.moves.iter() {
            if filter.is_match(&board) {
                return true;
            }
            if let Ok(update) = mv.make_move(&board) {
                board = update;
            } else {
                panic!("Illegal move found in game: {}", mv);
            }
        }
        filter.is_match(&board)
    }

    /// Writes game to the out_file stream in PGN format.
    pub(super) fn to_file(&self, out_file: &mut dyn std::io::Write) -> std::io::Result<()> {
        // Seven tag roster
        let roster = ["Event", "Site", "Date", "Round", "White", "Black", "Result"];

        // first write out elements IN the roster
        for key in roster.iter() {
            if self.header.contains_key(&key.to_string()) {
                out_file.write_all(
                    format!(
                        "[{} \"{}\"]\n",
                        key,
                        self.header.get(&key.to_string()).unwrap()
                    )
                    .as_bytes(),
                )?;
            }
        }

        // then write out remaining elements NOT in the roster
        for (key, val) in self.header.iter() {
            if !roster.contains(&key.as_str()) {
                out_file.write_all(format!("[{} \"{}\"]\n", key, val).as_bytes())?;
            }
        }
        out_file.write_all(b"\n")?;

        let mut moves = String::from("");
        for (n, mv) in self.moves.iter().enumerate() {
            if n % 2 == 0 {
                moves.push_str(&format!("{}. ", (n / 2) + 1));
            }
            moves.push_str(&mv.to_string());
            moves.push(' ');
        }
        moves.push_str(&self.result);
        moves.push_str("\n");

        for line in textwrap::wrap(&moves, 80).iter() {
            out_file.write_all(line.as_bytes())?;
            out_file.write_all(b"\n")?;
        }

        Ok(())
    }

    /// Returns the total number of half moves in this game.
    ///
    pub fn total_half_moves(&self) -> usize {
        self.moves.len()
    }

    /// An iterator on the game consists of a sequence of (Board, next_move) pairs.
    /// The next_move value is a string describing the next move to be played,
    /// until the last board position, when next_move is the game result.
    ///
    /// Information about move number, who is to move, etc are all accessible
    /// through methods on the board.
    ///
    /// # Example
    ///
    /// Given a game, the following will loop through and show all the
    /// board positions and moves of the given game:
    ///
    /// ```ignore
    /// for (board, mv) in game.iter() {
    ///     println!("{}", board);
    ///     println!("Move {}: {}{}",
    ///              board.fullmove_number(),
    ///              if board.player_to_move() == "White" { "" } else { "..." },
    ///              mv
    ///              );
    ///     println!("");
    /// }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if an invalid move occurs.
    ///
    pub fn iter(&self) -> GameIter {
        GameIter {
            game: &self,
            board: self.start_position(),
            posn: 0,
        }
    }

    // Return the start position for the game.
    // PGN games may provide a start-position under the key "fen",
    // if they do not begin from the start position.
    //
    // Panics if given an invalid fen
    fn start_position(&self) -> Board {
        if self.header.contains_key("fen") {
            if let Ok(board) = Board::from_fen(&self.header.get("fen").unwrap()) {
                board
            } else {
                panic!("Invalid start position given in FEN");
            }
        } else {
            Board::start_position()
        }
    }
}

/// Iterator object for a Game.
///
/// Calls to 'next' return a sequence of (Board, next_move) pairs.
///
pub struct GameIter<'a> {
    game: &'a Game,
    board: Board,
    posn: usize,
}

impl<'a> Iterator for GameIter<'a> {
    type Item = (Board, String);

    fn next(&mut self) -> Option<Self::Item> {
        if self.game.moves.is_empty() {
            None
        } else if self.posn <= self.game.moves.len() {
            if self.posn > 0 {
                // make the last returned move
                let curr_move = &self.game.moves[self.posn - 1];
                if let Ok(new_board) = curr_move.make_move(&self.board) {
                    self.board = new_board;
                } else {
                    panic!("Illegal move found in game: {}", curr_move);
                }
            }
            self.posn += 1;
            if self.posn - 1 < self.game.moves.len() {
                Some((
                    self.board.clone(),
                    self.game.moves[self.posn - 1].to_string(),
                ))
            } else {
                // we played the last move, so next move is the result
                Some((self.board.clone(), self.game.result.clone()))
            }
        } else {
            None
        }
    }
}
